<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\model;

use buwang\base\BaseModel;
use buwang\traits\JwtTrait;

/**管理员表
 * Class BwAuthNode
 * @package app\manage\model
 */
class Admin extends BaseModel
{
    protected $pk = 'id';

    protected $updateTime = 'updatetime';

    protected $deleteTime = 'updatetime';

    use JwtTrait;

    /*
* 设置查询初始化条件
* @param string $alias 表别名
* @param object $model 模型实例化对象
* @return object
* */
    public static function valiWhere($alias = '', $model = null)
    {
        $model = is_null($model) ? new self() : $model;
        if ($alias) {
            $model = $model->alias($alias);
            $alias .= '.';
        }
        // return  $model->where("{$alias}delete_time", 0);
        return $model;
    }

    /** 根据输入密码得到 加密后的密码串和盐
     * @param $password
     * @return array
     */
    public static function getPassword($password, $salt = null)
    {

        if (!$salt) $salt = self::getSalt();
        $salt1 = md5($salt);
        $password = $password = md5(md5(md5($password) . $salt1 . 'buwang'));  //把密码进行md5加密然后和salt连接
        return compact('password', 'salt');  //返回散列
    }

    public static function getSalt()
    {
//        $intermediateSalt = md5(uniqid(rand(), true));
//        $salt = substr($intermediateSalt, 0, 6);
        $salt = get_num_code();
        return $salt;
    }

    public static function createAdmin($param, $trans = false)
    {
        if (!isset($param['username']) || !$param['username']) return self::setError('用户名不存在');
        if (!isset($param['nickname']) || !$param['nickname']) return self::setError('昵称不存在');
        if (!isset($param['email']) || !$param['email']) return self::setError('电子邮箱不存在');
        if (!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)(?!\\W+$)[0-9A-Za-z\\W]{8,16}$/", $param['password'])) return self::setError('密码条件：8-16位字符必须是（英文/数字/特殊符号）至少两种的组合');
        if (!preg_match("/^[a-zA-Z\d_]{5,}$/", $param['username'])) return self::setError('用户名请使至少5位不能带中文和特殊符号');
        // var_dump($id);die;//常用函数
        $admin = self::where('username', $param['username'])->find();
        if ($admin) return self::setError('用户名已存在');
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //创建账号
            //得到账号密码

            //加密得到密文和盐
            $passinfo = self::getPassword($param['password']);
            $result = new self;
            $result['password'] = $passinfo['password'];
            $result['salt'] = $passinfo['salt'];
            $result['username'] = $param['username'];
            $result['nickname'] = $param['nickname'];
            $result['email'] = $param['email'];
            $result['status'] = $param['status'];
            $result['createtime'] = time();
            $res1 = $result->save();
            //$res1 = Admin::create($param);
            $res2 = AuthGroupAccess::updateRule($result['id'], explode(",", $param['rule_ids']), 'admin', false);
            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('删除角色失败');
            if (!$res2) return self::setError('插入角色失败');
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('更新角色失败');

        return $res;

    }

    public static function updateAdmin($param, $trans = false)
    {
        $topAdminId = config('auth.super_admin_id');//超级管理员id
        if (isset($param['password'])) {
            if (!$param['password']) {
                unset($param['password']);
            } else {
                if (!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)(?!\\W+$)[0-9A-Za-z\\W]{8,16}$/", $param['password'])) return self::setError('密码条件：8-16位字符必须是（英文/数字/特殊符号）至少两种的组合');

                if (isset($param['password2'])) {
                    if ($param['password2'] != $param['password']) return self::setError('两次输入的密码不一致');
                    unset($param['password2']);
                }

            }


        }
        if (isset($param['username'])) {
            if (!preg_match("/^[a-zA-Z\d_]{5,}$/", $param['username'])) return self::setError('用户名请使至少5位不能带中文和特殊符号');

            $admin = self::where('username', $param['username'])->where('id', 'not in', $param['id'])->find();
            if ($admin) return self::setError('用户名已存在');
        }
        if (isset($param['nickname']) && !$param['nickname']) return self::setError('昵称不存在');
        if (isset($param['email']) && !$param['email']) return self::setError('电子邮箱不存在');
        // var_dump($id);die;//常用函数
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //加密得到密文和盐
            if (isset($param['password'])) {
                $passinfo = self::getPassword($param['password']);
                $param['password'] = $passinfo['password'];
                $param['salt'] = $passinfo['salt'];
            }
            $res1 = Admin::update($param);

            if ($param['id'] != $topAdminId) {
                $res2 = AuthGroupAccess::updateRule($param['id'], explode(",", $param['rule_ids']), 'admin', false);
            }

            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('删除角色失败');
            if (!$res2) return self::setError(AuthGroupAccess::getError('插入角色失败'));
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('更新角色失败');

        return $res;

    }


    // 获取菜单列表
    public static function getMenuList($admin_id, $where = [])
    {

        $node_model = AuthNode::adminAuthWhere($admin_id, 'system', 'admin', '', false, $where);
        if (!$node_model) return [];
        $menuList = $node_model->field('id,pid,menu_path as href,title,icon,target,param')
            ->order('sort desc, id desc')
            ->select()
            ->toArray();
        if (!$menuList) return [];
        //组合数据
        foreach ($menuList as $i => &$node) {
            //有参数的拼参数
            if ($node['param']) $node['href'] .= '?' . $node['param'];
            unset($menuList[$i]['param']);
        }
        $menuList = self::buildMenuChild(0, $menuList);
        return $menuList;
    }

    //递归获取子菜单
    public static function buildMenuChild($pid, $menuList)
    {
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = self::buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['child'] = $child;
                    $node['href'] = '';//存在子菜单则父级无url
                }
                // todo 后续此处加上用户的权限判断
                $treeList[] = $node;
            }
        }
        return $treeList;
    }


    /**判断登录密码是否正确
     * @param $username
     * @param $password
     */
    public static function validateLogin($username, $password)
    {
        //判断用户是否存在
        $admin = self::where('username|email', $username)->find();
        if (!$admin) return self::setError('用户名或密码错误');
        if ($admin['status'] == 0) return self::setError('账号已被封禁无法登陆');
        //得到加密后的密码
        $passWordInfo = self::getPassword($password, $admin['salt']);

        if ($admin['password'] != $passWordInfo['password']) return self::setError('用户名或密码错误');
        //查询用户组
        $group_ids = AuthGroupAccess::where('uid', $admin['id'])->column('group_id');
        $admin['group_id'] = implode(",", $group_ids);//数组合并成字符串
        return $admin;
    }


    public static function loginAdmin($admin, $trans = false)
    {
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = $tokenInfo = true;
        try {
            $data = [
                'id' => $admin['id'],
                'nickname' => $admin['nickname'],
                'mobile ' => '',
            ];
            $tokenInfo = self::getAccessToken($data, 'admin');
            //存儲token相关信息
            // $res2 = Token::updateToken($admin['id'], $tokenInfo['token'], 'admin');
            //更新用户登录信息
            $admin->logintime = time();
            $admin->loginip = request()->ip();
            $res1 = $admin->save();

            $res = $res1 && $res2 && $tokenInfo && true;
            if ($trans) {
                self::checkTrans($res);
            }

        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$tokenInfo) return self::setError(self::getError());
        if (!$res1) return self::setError('更新用户登录信息失败');
        if (!$res2) return self::setError('更新用户验证信息失败');
        return $tokenInfo;

    }


}
